<template>
    <div class='works-detail'>
        <!--        封面-->
        <div class='cover'>
            <img src='@/assets/images/login-background.jpg' alt='background'>
        </div>
        <div class='content-main'>
            <!--        面包屑-->
            <div class='crumbs'>
                <breadcrumb
                    id='breadcrumb-container' :competitionId='works.competitionId' :judgeIds='judgeIds?.join(",")||""'
                    class='breadcrumb-container' />
            </div>
            <div class='works-detail-content'>
                <div class='left'>
                    <div class='title'>{{ works?.title || '作品标题' }}</div>
                    <div class='icons'>
                        <div class='icons-left'>
                            <div class='icons-left-avatar'>
                                <img v-if='works?.user?.avatar' :src='`/api${works?.user?.avatar}`' alt='avatar'>
                                <img v-else src='@/assets/images/profile.jpg' alt='profile'>
                            </div>
                            <div class='icons-left-text'>{{ works?.user?.nickName || '作者名称' }}</div>
                        </div>
                        <div class='icons-right'>
                            <!--作品是本人不展示 关注按钮-->
                            <template v-if='userStore?.userInfo?.userId!==works?.user?.userId'>
                                <div class='icons-right-img'>
                                    <img src='@/assets/index/focus.png' alt='focus'>
                                </div>
                                <el-link
                                    v-if='focusStatus' type='primary' :underline='false' class='icons-right-text'
                                    @click='focusHandler(works?.user?.userId as number)'>已关注
                                </el-link>
                                <el-link v-else :underline='false' class='icons-right-text'
                                         @click='focusHandler(works?.user?.userId as number)'>
                                    点击关注
                                </el-link>
                            </template>

                        </div>
                    </div>
                    <div class='works-info'>
                        <div class='works-desc'>
                            作品介绍
                        </div>
                        <div class='works-desc-content'>
                            {{ works?.description || '作品描述' }}
                        </div>
                    </div>
                    <div class='works-attachment'>
                        <div class='works-attachment-header'>作品附件</div>
                        <div class='works-file'>
                            <el-link
                                v-for="file in works?.attachments?.split(',')||[]" :key='file' :underline='false'
                                :href='`/api${file}`'>
                                {{ (file.slice(file.lastIndexOf('/') + 1)).split('_')[0] }}
                            </el-link>
                        </div>
                    </div>
                    <div class='works-function'>
                        <!--点评作品-->
                        <!--是当前赛事评委才展示-->
                        <div v-if='judgeIds?.length&&judgeIds.includes(userStore?.userInfo.userId)'>
                            <div v-if='form.markId' class='revamp-comment' @click='markHandler'>
                                <div class='comment-img'><img src='@/assets/index/edit-a.png' alt='edit'></div>
                                <el-link :underline='false' type='primary'>修改点评</el-link>
                            </div>
                            <div v-else class='revamp-comment' @click='markHandler'>
                                <div class='comment-img'><img src='@/assets/index/edit.png' alt='edit'></div>
                                <el-link :underline='false' type='info'>点评作品</el-link>
                            </div>
                        </div>

                        <!--收藏作品-->
                        <div>
                            <div v-if='collectStatus' class='cancel-collect' @click='collectWorksHandler'>
                                <div class='collect-img'><img src='@/assets/index/collect-a.png' alt='collect'></div>
                                <el-link :underline='false' type='warning'>取消收藏</el-link>
                            </div>
                            <div v-else class='cancel-collect' @click='collectWorksHandler'>
                                <div class='collect-img'><img src='@/assets/index/collect2.png' alt='collect'></div>
                                <el-link :underline='false' type='info'>收藏作品</el-link>
                            </div>
                        </div>
                    </div>
                </div>
                <div class='right'>
                    <div class='title'>评委评分</div>
                    <div class='judges' v-if='markList.length'>
                        <div v-for='mark in markList' :key='mark.markId' class='judge'>
                            <div class='header'>
                                <div class='judge-info'>
                                    <div class='avatar'>
                                        <img v-if='mark.user.avatar' :src='`/api${mark.user.avatar}`' alt='avatar'>
                                        <img v-else src='@/assets/images/profile.jpg' alt='profile'>
                                    </div>
                                    <div class='nickname'>{{ mark.user.nickName }}</div>
                                </div>
                                <div class='num'>{{ mark?.score || 0 }}分</div>
                            </div>
                            <div class='content'>{{ mark?.comment || '暂无评语' }}</div>
                        </div>
                    </div>
                    <div class='judges empty' v-else>
                        暂无评委评分
                    </div>

                </div>
            </div>
        </div>

        <!--        评论区域-->
        <div class='comment-container'>
            <!--            评论区主要展示区域-->
            <div class='comment-main-content'>
                <div class='comment-title'><span>评论区</span>
                </div>
                <template v-if='commentList.length'>
                    <div
                        v-for='comment in commentList'
                        :key='comment.commentId'
                        class='comment-box'>
                        <div class='top-header'>
                            <img
                                v-if='comment?.user?.avatar' class='avatar' :src='`/api${comment?.user?.avatar}`'
                                alt='avatar'>
                            <img v-else class='avatar' src='@/assets/images/profile.jpg' alt='avatar'>
                            <div class='comment-nickname-time'>
                                <div class='nickname'>{{ comment?.user?.nickName }}</div>
                                <div class='time'>
                                <span>{{ (formatTime(new Date(comment?.createTime).getTime(), '{y}-{m}-{d} {h}:{i}:{s}'))
                                    }}</span>·<span>{{ comment?.addr || '未知' }}</span></div>
                            </div>
                        </div>
                        <div class='comment-content'>
                            {{ comment.content }}
                        </div>
                        <div class='opers'>
                            <el-button type='primary' link class='reply' @click='replyHandler(comment)'>回复</el-button>
                            <el-button
                                v-if='comment.subTotal&&!comment.open' link
                                class='reply'
                                @click='openChildCommentHandler(comment )'><span
                                style='margin-right: 4px;'>展开{{ comment.subTotal }}条回复</span>
                                <el-icon>
                                    <ArrowDown />
                                </el-icon>
                            </el-button>
                        </div>
                        <!--                        2+n级评论-->
                        <div class='more-comments'>
                            <div class='sub-comments'>
                                <template v-if='comment.subComment?.length'>
                                    <div
                                        v-for='subComment in comment.subComment'
                                        :key='subComment.commentId' class='sub-comment-item'>
                                        <div class='sub-comment-header'>
                                            <img
                                                v-if='subComment?.user?.avatar' class='avatar' :src='`/api${subComment?.user?.avatar}`'
                                                alt='avatar'>
                                            <img v-else class='avatar' src='@/assets/images/profile.jpg' alt='avatar'>
                                            <div class='comment-nickname-time'>
                                                <div v-if='comment.commentId===subComment.parentId' class='nickname'>
                                                    {{ subComment?.user?.nickName }}
                                                </div>
                                                <div v-else class='nickname'>{{ subComment?.user?.nickName }}
                                                    <el-icon color='#CDD0D6'>
                                                        <CaretRight />
                                                    </el-icon>
                                                    {{ subComment?.receiveUser?.nickName }}
                                                </div>
                                                <div class='time'>
                                <span>{{ (formatTime(new Date(subComment?.createTime).getTime(), '{y}-{m}-{d} {h}:{i}:{s}'))
                                    }}</span>·<span>{{ subComment.addr }}</span></div>
                                            </div>
                                        </div>
                                        <div class='sub-comment-content'>
                                            {{ subComment.content }}
                                            <el-button
                                                style='margin-left: 10px;' type='primary'
                                                link class='reply' @click='replyHandler(subComment)'>
                                                回复
                                            </el-button>
                                        </div>


                                    </div>
                                </template>
                            </div>
                        </div>
                    </div>
                    <div v-if='commentList.length<commentTotal' class='comment-box more'>
                        <el-button link type='info' @click='moreLoadHandler'>加载更多</el-button>
                    </div>
                </template>

                <div v-else class='comment-box empty' style='min-height:350px;'>暂无评论,快来占个沙发叭~</div>
            </div>
            <!--            发布评论的区域-->
            <CommentPublish
                v-model:reply-info='replyInfo' :data-id='works.worksId'
                type='works' @success='commentPublishSuccess' />
        </div>

        <!--        作品点评-->
        <Teleport to='body'>
            <div class='modal' @click='closeHandler' v-if='open'></div>
            <transition>
                <div class='mark-container' v-if='open'>
                    <div class='mark-header'>
                        <span>作品点评</span>
                        <el-icon @click='closeHandler' style='cursor: pointer;' size='20' color='#CE6043'>
                            <Close />
                        </el-icon>
                    </div>
                    <div class='mark-form'>
                        <el-form ref='markFormRef' :model='form' :rules='rules' label-position='top'>
                            <el-form-item label='作品分数' prop='score'>
                                <el-input-number
                                    v-model='form.score' class='ff' placeholder='请输入分数' :min='0'
                                    :max='10' />
                            </el-form-item>
                            <el-form-item label='作品点评' prop='comment'>
                                <el-input show-word-limit maxlength='50' v-model='form.comment' type='textarea'
                                          placeholder='请输入点评内容' />
                            </el-form-item>
                            <el-form-item class='btns'>
                                <el-button @click='submit' type='primary'>确定
                                </el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                </div>
            </transition>
        </Teleport>
    </div>
</template>

<script lang='ts' setup>
import { useRoute } from 'vue-router';
import { getWorks } from '@/api/business/works';
import type { Ref } from 'vue';
import { getCurrentInstance, onMounted, reactive, ref, toRefs, watch } from 'vue';
import { _Works } from '@/api/model/Works';
import { Views } from '@/api/model/Views';
import { addViews } from '@/api/business/brower';
import useUserStore from '@/store/modules/user';
import { collect, isCollect } from '@/api/business/collect';
import { isRelogin } from '@/utils/request';
import { addWorksMark, editWorksMark, initWorksMark, listWorksMark } from '@/api/business/mark';
import { WorksMark } from '@/api/model/WorksMark';
import { focus, isFocus } from '@/api/business/focus';
import { formatTime } from '@/utils/sk';
import CommentPublish from '@/components/JhCommentPublish/index.vue';
import { _Comment } from '@/api/model/Comment';
import { listFirstComment, selectChildByRootId } from '@/api/business/comment';

const commentTotal = ref(0);
const markList: Ref<WorksMark[]> = ref([]);
const worksId = ref<number | string>();
const userStore = useUserStore();
const open = ref(false);
const collectStatus = ref(false);//收藏状态
const focusStatus = ref(false);//关注状态
const works: Ref<_Works> = ref({});
const judgeIds = ref<number[]>([]);
const commentList = ref<_Comment[]>([]);
const replyInfo = ref<{ nickName?: string, commentId?: number }>({});
const data = reactive({
    form: {
        score: 0,
        comment: '',
        markId: 0,
        worksId: 0
    },
    rules: {
        score: [{ required: true, message: '请输入作品分数', trigger: 'blur' }],
        comment: [{ required: true, message: '请输入点评内容', trigger: 'blur' }]
    },
    commentParams: {
        pageNum: 1, pageSize: 10, dataId: -1, type: 'works'
    }
});
const { form, rules, commentParams } = toRefs(data);
const { proxy } = getCurrentInstance();
const route = useRoute();

/*获取一级评论列表*/
const getFirstCommentList = async () => {
    commentParams.value.dataId = works.value.worksId || -1;
    await listFirstComment(commentParams.value).then(res => {
        res.rows.forEach((x: _Comment) => x.open = false);//给每一个评论添加打开状态
        commentList.value = [...commentList.value, ...res.rows];
        commentTotal.value = res.total;
    });

};
/*评论/回复 成功回调 */
const commentPublishSuccess = async (commentId: number | null) => {
    commentParams.value.pageNum = 1;
    commentList.value = [];
    await getFirstCommentList();//获取评论
    const find = commentList.value.find(x => x.commentId === commentId);//查找父级
    if (find) {
        // 打开子集评论
        openChildCommentHandler(find);
    }
    replyInfo.value = {};
};

/*展开子集评论*/
const openChildCommentHandler = (comment: _Comment) => {
    const parentId = comment.commentId;//父级Id
    // 获取父级下面所有评论
    selectChildByRootId(parentId as number).then(res => {
        comment['subComment'] = res.rows;
        comment['open'] = true;
    });
};

/*回复*/
const replyHandler = (comment: _Comment) => {
    // 回复人信息
    replyInfo.value = {
        commentId: comment.commentId,
        nickName: '@' + comment.user?.nickName.concat(' ')
    };
};
/*加载更多评论*/
const moreLoadHandler = () => {
    commentParams.value.pageNum += 1;
    // 获取一级评论
    getFirstCommentList();
};
const reset = () => {
    // form.value = {
    //     score: 0,
    //     comment: '',
    //     markId: 0,
    //     worksId: 0
    // };
    // proxy.resetForm('markFormRef');
    // 如果没有打分记录
    if (!form.value.markId) {
        // 初始化打分详情
        initWorksMarkHandler();
    }
    form.value.worksId = worksId.value as number;//作品Id
};
/*关注*/
const focusHandler = (receiveId: number | string) => {
    if (!userStore.isLogin) isRelogin.show = true;
    if (!receiveId) return;
    // 关注 取消关注
    focus(receiveId).then(() => {
        getFocusStatus(receiveId);
    });
};
/*获取关注状态*/
const getFocusStatus = (receiveId: number | string) => {
    if (!userStore.isLogin) return;
    if (!receiveId) return proxy.$modal.msgError('关注人Id:[receiveId]不存在!');
    // 关注状态
    isFocus(receiveId).then(res => {
        focusStatus.value = res.data;
    });
};
/*关闭弹出层*/
const closeHandler = () => {
    open.value = false;
    reset();
};
/*获取作品详细*/
const getWorksHandler = () => {
    if (!worksId.value) return proxy.$modal.msgError('作品Id:[worksId]不存在!');
    getWorks(worksId.value).then(res => {
        works.value = res.data;
        addViewsHandler();//添加浏览
        isCollectHandler();//获取收藏状态
        getWorksMarkList();//获取作品打分列表
        initWorksMarkHandler();//初始化作品打分详细
        getFocusStatus(works.value.user?.userId as number);//获取关注状态
        getFirstCommentList();//获取评论
    });
};
/*浏览作品*/
const addViewsHandler = () => {
    const dataId = worksId.value;
    if (!dataId) return;
    const data: Views = {
        dataId: parseInt(dataId as string),
        type: 'works'
    };
    addViews(data);
};
/*点评作品*/
const markHandler = () => {
    // 初始化打分详情
    initWorksMarkHandler();
    open.value = true;
};
/*收藏作品*/
const collectWorksHandler = () => {
    if (!userStore.isLogin) return isRelogin.show = true;
    if (!worksId.value) return;
    /*收藏 取消收藏 并且获取收藏状态*/
    collect(worksId.value, 'works').then(() => isCollectHandler());
};
/**
 * 获取收藏状态
 */
const isCollectHandler = async () => {
    if (!userStore.isLogin) return;
    if (!worksId.value) return;
    // 获取收藏状态
    isCollect(worksId.value, 'works').then(res => {
        collectStatus.value = res.data;
    });
};
/*提交*/
const submit = () => {
    if (!worksId.value) return proxy.$modal.msgError('作品Id不存在!');
    proxy.$refs['markFormRef'].validate((validate: boolean) => {
        if (validate) {
            form.value.worksId = worksId.value as number;//作品Id
            if (form.value?.markId) {
                // 修改打分
                editWorksMark(form.value).then(() => {
                    proxy.$modal.msgSuccess('修改作品点评成功!');
                    closeHandler();
                    getWorksMarkList();//获取评分列表
                });
            } else {
                // 添加打分
                addWorksMark(form.value).then(() => {
                    proxy.$modal.msgSuccess('作品点评成功!');
                    closeHandler();
                    getWorksMarkList();//获取评分列表
                });
            }
        }
    });
};
/*初始化打分详细*/
const initWorksMarkHandler = () => {
    if (!userStore.isLogin) return;
    if (!worksId.value) return;
    /*如果有记录*/
    if (form.value.markId && form.value.score && form.value.comment) return;
    initWorksMark(worksId.value).then(res => {
        /*如果有记录*/
        if (res?.data) {
            form.value = res.data;
        }
    });
};
/*获取评分打分列表*/
const getWorksMarkList = () => {
    listWorksMark({ worksId: worksId.value }).then(res => {
        markList.value = res.rows;
    });
};
watch(() => userStore.isLogin, () => {
    collectStatus.value = false;
    form.value.markId = 0;//评分Id
    form.value.comment = '';//评论
    form.value.score = 0;//评分
    focusStatus.value = false;
    isCollectHandler();//比赛收藏状态
    initWorksMarkHandler();//初始化打分详细
    getFocusStatus(works.value.user?.userId as number);//获取关注状态
    replyInfo.value = {};//回复人信息

});
onMounted(() => {
    const _ids = route.query?.judgeIds as string;
    if (_ids && _ids.split(',').length > 0) {
        judgeIds.value = _ids.split(',').map(id => parseInt(id));
    }
    worksId.value = route.params?.worksId as string;//作品Id
    getWorksHandler();//获取作品详细
    initWorksMarkHandler();//初始化打分详细
});
</script>

<style scoped lang='scss'>
.more-comments {
    padding-left: 60px;
    margin-top: 10px;

    .nickname {
        color: rgba(0, 0, 0, 0.7);
        display: flex;
        align-items: center;
        margin-bottom: 4px;

        i {
            margin: 0 6px;
        }
    }

    .sub-comment-item {
        margin-top: 10px;

        &.my-comment {
            .sub-comment-header {
                justify-content: flex-end;
            }

            .sub-comment-content {
                text-align: right;

            }
        }
    }

    .avatar {
        width: 30px;
        height: 30px;
        border-radius: 50%;
        object-fit: cover;
        margin-right: 10px;
    }

    .sub-comment-content {
        padding-left: 40px;
        font-size: 16px;
        display: flex;
        align-items: center;
        margin-top: 10px;
    }

    .sub-comment-header {
        display: flex;
        color: rgba(0, 0, 0, 0.5);
        align-items: center;


    }

    .comment-nickname-time {
        font-size: 12px;
    }
}

.comment-container {
    margin-top: 20px;
    //padding: 0 670px 0 250px;
    padding: 0 250px;
    display: flex;
    position: relative;
    align-items: flex-start;


    .comment-main-content {
        width: 1000px;
        border-radius: 4px;
        margin-right: 20px;
    }

    .comment-title {
        font-size: 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 20px;
    }

    .top-header {
        display: flex;
        color: rgba(0, 0, 0, 0.5);

        .comment-nickname-time {
            display: flex;
            flex-direction: column;
            justify-content: space-between;

            .nickname {
                color: rgba(0, 0, 0, 0.7);
            }

            .time {
                font-size: 14px;
            }
        }

        .avatar {
            width: 50px;
            height: 50px;
            object-fit: cover;
            border-radius: 50%;
            margin-right: 10px;
        }
    }

    .comment-content {
        padding-left: 60px;
        margin-top: 10px;
        //padding-right: calc(50% - 20px);
        font-size: 18px;
    }

    .opers {
        display: flex;
        flex-direction: column;
        align-items: flex-start;

        .reply {
            padding-left: 60px;
            margin: 5px 0;
        }
    }

    .comment-box {
        background: #fff;
        border-radius: 4px;
        padding: 20px;
        border-bottom: 1px #efefef solid;

        &.more {
            text-align: center;
        }

        &.my-comment {
            .top-header {
                justify-content: flex-end;
            }

            .comment-content {
                text-align: right;
                padding-left: calc(50% - 20px);
                padding-right: 60px;
            }

            .opers {
                align-items: flex-end;
            }

            .avatar {
                order: 2;
                margin-right: 0;
                margin-left: 10px;
            }

            .comment-nickname-time {
                order: 1;
                align-items: flex-end
            }
        }
    }

}

.modal {
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1;
    background: rgba(0, 0, 0, 0.5);
    position: fixed;
}

.mark-container {
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 400px;
    min-height: 250px;
    background: #fff;
    z-index: 2;
    position: fixed;
    border-radius: 4px;
    padding: 16px;

    .mark-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .mark-form {
        margin-top: 15px;
    }

    :deep(.el-form-item__label) {
        font-weight: 500;
    }

    :deep(.el-textarea__inner) {
        resize: none;
        min-height: 100px !important;
    }

    .btns {
        margin-bottom: 0 !important;

        button {
            width: 80px;
        }

        :deep(.el-form-item__content) {
            justify-content: flex-end;
        }
    }
}

.works-detail {
    .cover {
        height: 350px;

        img {
            height: 100%;
            width: 100%;
            object-fit: cover;
        }
    }

    .content-main {
        padding: 0 250px;
    }

    .crumbs {
        display: flex;
        align-items: center;
        margin: 20px 0;

    }

    .works-detail-content {
        display: flex;
        align-items: flex-start;

        .left, .right {
            border-radius: 6px;
            background: #FFFFFF;
        }

        .left {
            width: 1000px;
            //height: 2000px;
            margin-right: 20px;
            padding: 0 20px;

            .title {
                text-align: center;
                line-height: 67px;
                height: 67px;
                font-weight: 900;
                font-size: 20px;
            }

            .icons {
                height: 70px;
                font-size: 18px;
                color: #3D3D3D;
                display: flex;
                justify-content: right;
                align-items: center;

                .icons-left {
                    display: flex;
                    align-items: center;
                    margin-right: 10px;


                    .icons-left-avatar {
                        border-radius: 25px;
                        width: 50px;
                        height: 50px;
                        margin-right: 10px;

                        img {
                            border-radius: 25px;
                        }
                    }
                }

                .icons-right {
                    display: flex;
                    font-size: 14px;
                    align-items: center;
                    cursor: pointer;

                    .icons-right-img {
                        margin-right: 5px;
                    }
                }
            }

            .works-info {
                color: #3D3D3D;

                .works-desc {
                    font-size: 18px;
                }

                .works-desc-content {
                    font-size: 16px;
                    padding: 10px 0;
                }
            }

            .works-attachment {
                padding: 10px 0;
                color: #3D3D3D;

                .works-attachment-header {
                    font-size: 18px;
                    color: #409EFF;
                }

                .works-file {
                    font-size: 16px;
                    padding: 10px 0;

                    span {
                        cursor: pointer;
                    }
                }
            }

            .works-function {
                font-size: 14px;
                display: flex;
                justify-content: right;
                height: 70px;

                .revamp-comment {
                    color: #409EFF;
                    margin-right: 10px;
                    display: flex;
                    align-items: center;
                    cursor: pointer;

                    .comment-img {
                        margin-right: 5px;
                    }
                }

                .cancel-collect {
                    color: #FA8511;
                    display: flex;
                    align-items: center;
                    cursor: pointer;

                    .collect-img {
                        margin-right: 5px;
                    }
                }
            }
        }

        .right {
            flex: 1;
            overflow: hidden;
            position: sticky;
            top: 10px;

            .title {
                padding: 17px 0;
                background: rgba(64, 158, 255, 0.8);
                font-size: 20px;
                font-weight: 500;
                color: #FFFFFF;
                text-align: center;
            }
        }

        .judges {
            padding: 20px;

            .header {
                display: flex;
                align-items: center;
                justify-content: space-between;
            }

            .content {
                margin-top: 10px;
                padding-left: 50px;
            }

            .judge {
                margin-bottom: 20px;
                display: flex;
                flex-direction: column;
                border-bottom: 1px solid #efefef;
                padding-bottom: 10px;

                &:last-child {
                    padding-bottom: 0;
                    border: none;
                }

                .num {
                    font-size: 16px;
                    font-weight: 400;
                    color: rgba(0, 0, 0, 0.5);
                }
            }

            .judge-info {
                display: flex;
                align-items: center;
            }

            .nickname {
                font-size: 20px;
                font-weight: 500;
                color: #3D3D3D;
                margin-left: 10px;
            }

            .avatar {
                width: 40px;
                height: 40px;
                border-radius: 50%;
                overflow: hidden;

                img {
                    width: 100%;
                    height: 100%;
                }
            }
        }
    }
}
</style>
